/*
 * *
 *  * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 *
 *
 */

package com.iwindplus.mgt.server;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Set;
import java.util.function.Function;

/**
 * TopLevelFinder.
 *
 * @author zengdegui
 * @since 2024-10-18
 */
public class TopLevelFinder {
    public static <T> T findTopLevel(T current, Set<T> allElements, Function<T, T> parentFetcher) {
        T parent = parentFetcher.apply(current);
        if (parent == null) {
            // 当前元素没有父元素，它就是最顶级的
            return current;
        }
        // 递归查找最顶级的父元素
        return findTopLevel(parent, allElements, parentFetcher);
    }

    public static void main(String[] args) {
        // 示例：使用Hutool的Lists和Sets工具类
        List<Item> items = Lists.newArrayList(
                new Item(1, "Item1", 0),
                new Item(2, "Item2", 1),
                new Item(3, "Item3", 1),
                new Item(4, "Item4", 2)
        );

        // 假设我们有一个获取父元素的函数
        Function<Item, Item> parentFetcher = item -> {
            for (Item other : items) {
                if (other.getId() == item.getParentId()) {
                    return other;
                }
            }
            return null;
        };

        // 找到ID为4的元素的最顶级父元素
        Item topLevelItem = findTopLevel(items.get(3), CollectionUtil.newHashSet(items), parentFetcher);
        System.out.println("最顶级的父元素是: " + topLevelItem.getName());
    }

    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    static class Item {
        private int id;
        private String name;
        private int parentId;
    }
}
